package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.w3c.dom.UserDataHandler;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    //保存
    @Override
    public String save(Movement movement) {
        String name = Thread.currentThread().getName();
        System.out.println("主线程的名字：" + name);

        //1. 保存到动态表
        mongoTemplate.save(movement);

        //2. 调用timeLineService，异步保存关系表数据
        timeLineService.saveTimeLine(movement);

        return movement.getId().toString();
    }

    //根据userID查询
    @Override
    public List<Movement> findUserId(Long userId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1); //查询审核状态通过的
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pageSize)
                .limit(pageSize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }

    //根据id查询
    @Override
    public List<Movement> findByFriendId(Long friendId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pageSize)
                .limit(page);

        //1. 查询出关系表
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2. 获取出所有我可以看的动态id
        List<ObjectId> ids = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //3. 根据ids获取出动态集合
        Criteria criteria1 = Criteria.where("id").in(ids);
        Query query1 = Query.query(criteria1);
        return mongoTemplate.find(query1, Movement.class);
    }

    //根据ids查询（动态推荐）
    @Override
    public List<Movement> findByMovementIds(String[] movementIds, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("id").in(movementIds);
        Query query = Query.query(criteria)
                .skip((page - 1) * pageSize)
                .limit(pageSize);
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    //随机查询（动态推荐）
    @Override
    public List<Movement> randomMovement(Integer pageSize) {
        TypedAggregation<Movement> aggregation = TypedAggregation.newAggregation(Movement.class, Aggregation.sample(pageSize));

        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        return results.getMappedResults();
    }

    //根据id查询动态
    @Override
    public Movement findById(String id) {
        Movement movement = mongoTemplate.findById(id, Movement.class);
        return movement;
    }

    //状态更新
    @Override
    public void updateState(String movementId, Integer state) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(movementId));
        Query query = Query.query(criteria);
        Update update = new Update();
        update.set("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }

    //根据用户id和状态进行查询
    @Override
    public PageResult findMovement(Integer page, Integer pagesize, Long uid, Integer states) {
        //Criteria criteria = Criteria.where("userId").is(uid).and("state").is(states);
        Criteria criteria = new Criteria();
        // 判断uid和states是否为空
        if (uid != null) {
            criteria.and("userId").is(uid);
        }
        if (states != null) {
            criteria.and("state").is(states);
        }
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, Movement.class);
        query = query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, count, movements);
    }


}
